package com.gjy.mongod.codec;

import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-17 14:19:22
 */
public class CustomerProvider implements CodecProvider {

    private final Map<Class<?>, Codec<?>> codecs = new HashMap<>();

    public CustomerProvider() {
        this.addCodecs();
    }

    @SuppressWarnings("all")
    @Override
    public <T> Codec<T> get(Class<T> aClass, CodecRegistry codecRegistry) {
        return (Codec<T>) this.codecs.get(aClass);
    }

    private void addCodecs() {
        this.addCodec(new LocalDateTimeCodec());
    }

    private <T> void addCodec(Codec<T> codec) {
        this.codecs.put(codec.getEncoderClass(), codec);
    }

    private static final class LocalDateTimeCodec implements Codec<LocalDateTime> {

        @Override
        public LocalDateTime decode(BsonReader reader, DecoderContext decoderContext) {
            String s = reader.readString();
            return LocalDateTime.parse(s);
        }

        @Override
        public void encode(BsonWriter writer, LocalDateTime localDateTime, EncoderContext encoderContext) {
            writer.writeString(localDateTime.toString());
        }

        @Override
        public Class<LocalDateTime> getEncoderClass() {
            return LocalDateTime.class;
        }
    }
}
